package cn.yudao.ymcc.security.service;

import cn.yudao.ymcc.domain.Login;
import cn.yudao.ymcc.domain.Permission;
import cn.yudao.ymcc.dto.UserInfoParamDto;
import cn.yudao.ymcc.mapper.PermissionMapper;
import cn.yudao.ymcc.service.ILoginService;
import cn.yudao.ymcc.service.IPermissionService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class LoginUserDetailsService implements UserDetailsService{

    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名查询用户
        Wrapper<Login> warpper = new EntityWrapper<>();
        warpper.eq("username",username);
        Login login = loginService.selectOne(warpper);
        // 判断用户是否存在
        if (login !=null){
            // 获取当前用户拥有的权限数据配置给当前用户--连表查询--还需要配置权限WebSecurityConfig--(早上说的是单表)
            List<Permission> permissions =  permissionMapper.selectPermissonByLoginId(login.getId());
            // 将数据装到security的UserDetails的实现类User
            List<SimpleGrantedAuthority> authorities = permissions.stream()
                    .map(per -> new SimpleGrantedAuthority(per.getSn())).collect(Collectors.toList());
           return new User(JSON.toJSONString(new UserInfoParamDto(login.getUsername(),login.getId())),login.getPassword()
                    ,login.getEnabled(),login.getAccountNonExpired(),login.getCredentialsNonExpired(),
                    login.getAccountNonLocked(),authorities);

        }
        return null;
    }
}
